#include "StdAfx.h"
#include "MAPICenter.h"
#include "SmartPtr.h"


CMAPICenter::CMAPICenter(void)
		: m_pAdviseSink(NULL)
{
	InitMAPI();
}

CMAPICenter::~CMAPICenter(void)
{
	ReleaseMAPI();
}

CMAPICenter* CMAPICenter::Instance()
{
	static Smart_ptr::SmartPtr<CMAPICenter> pMAPICenter;

	if ( NULL == pMAPICenter )
	{
		pMAPICenter = new CMAPICenter();
	}

	return pMAPICenter;
}

extern HRESULT GetSMSMsgStore(const CComPtr<IMAPISession>& spSession,
							  CComPtr<IMsgStore>& spMsgStore);
extern HRESULT GetSMSFolder(const CComPtr<IMsgStore>& spMsgStore,
							CComPtr<IMAPIFolder>& spFolder);
extern HRESULT SendSMSMessage(const CComPtr<IMAPIFolder>& spFolder,
							  LPCTSTR lpszFrom,
							  LPCTSTR lpszTo, LPCTSTR lpszMessage);

BOOL CMAPICenter::InitMAPI()
{
	HRESULT hr = ::MAPIInitialize(NULL);

	if ( FAILED(hr) )
	{
		return FALSE;
	}

	hr = ::MAPILogonEx(0 , NULL, NULL, 0, &m_spSession);

	if ( FAILED(hr) )
	{
		return FALSE;
	}

	hr = ::GetSMSMsgStore(m_spSession, m_spStore);

	if ( FAILED(hr) )
	{
		return FALSE;
	}

	return TRUE;
}

void CMAPICenter::UnAdviseSink()
{
	if ( NULL != m_pAdviseSink )
	{
		::MAPIlibUnadvise(m_pAdviseSink);
		m_pAdviseSink = NULL;
	}
}

void CMAPICenter::ReleaseMAPI()
{
	UnAdviseSink();

	if ( NULL != m_spStore )
	{
		m_spStore.Release();
	}

	if ( NULL != m_spSession )
	{
		m_spSession->Logoff(0, 0, 0);
		m_spSession.Release();
	}

	::MAPIUninitialize();
}

BOOL CMAPICenter::AdviseSink(AdviseSinkCallback pCallback)
{
	BOOL bResult = FALSE;

	CMAPICenter* pCenter = Instance();

	if ( NULL != pCenter->m_spStore )
	{
		pCenter->UnAdviseSink();

		const ULONG uEventMask = fnevNewMail | fnevObjectCreated;
		IMAPIAdviseSink* pAdviseSink = pCenter->m_pAdviseSink;
		::MAPIlibAdvise(pCenter->m_spStore, uEventMask, pCallback, &(pAdviseSink));
	}

	return bResult;
}

IMsgStore* CMAPICenter::GetSMSStore()
{
	CMAPICenter* pCenter = Instance();

	return pCenter->m_spStore;
}
